package org.example.pmsystem.service.Impl;

import org.example.pmsystem.entity.StaffLeave;
import org.example.pmsystem.mapper.AttendMapper;
import org.example.pmsystem.mapper.StaffLeaveMapper;
import org.example.pmsystem.service.StaffLeaveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class StaffLeaveServiceImpl implements StaffLeaveService {
    @Autowired
    private StaffLeaveMapper staffLeaveMapper;
    @Autowired
    private AttendMapper attendMapper;

    @Override
    public List<StaffLeave> getStaffLeaveBySno(String sNo) {
        return staffLeaveMapper.selectStaffLeaveBySno(sNo);
    }

    @Override
    public List<StaffLeave> getStaffLeaveByDep(String sDep) {
        return staffLeaveMapper.selectAllStaffLeaveByDep(sDep);
    }

    @Override
    public List<StaffLeave> getStaffLeaveByStatus(String status) {
        return staffLeaveMapper.selectAllStaffLeaveByStatus(status);
    }

    @Override
    public boolean insertStaffLeave(StaffLeave staffLeave) {
        LocalDate date = staffLeave.getStartDate();
        if (date!= null && date.isBefore(LocalDate.now()))
            return false;
        date = staffLeave.getEndDate();
        if (date!=null && date.isBefore(staffLeave.getStartDate()))
            return false;
        // 设置申请时间
        staffLeave.setAppTime(LocalDateTime.now());
        // 设置审核状态
        staffLeave.setAppStatus("1");
        staffLeaveMapper.insertStaffLeave(staffLeave);
        return true;
    }


    @Override
    public void updateStaffLeaveStatus(StaffLeave staffLeave) {
        staffLeaveMapper.updateStaffLeaveStatus(staffLeave);

        // 添加本月的请假次数
        if (staffLeave.getAppStatus().equals("4")){
            staffLeave = staffLeaveMapper.selectStaffLeaveByLeaveno(staffLeave.getLeaveNo());
            LocalDateTime time = staffLeave.getAppTime();
            // 获取日期
            int year,month;
            year = time.getYear();
            month = time.getMonthValue();
            String result = String.format("%d-%02d",year,month);

            if (attendMapper.selectAttendSumBySnoDate(staffLeave.getSNo(),result) == null)
                attendMapper.insertEmptyAttendSummary(staffLeave.getSNo(),result);

            attendMapper.addleaveTimes(staffLeave.getSNo(),result);
        }

    }

    @Override
    public boolean updateStaffLeave(StaffLeave staffLeave){
        LocalDate date = staffLeave.getStartDate();
        if (date!= null && date.isBefore(LocalDate.now()))
            return false;
        date = staffLeave.getEndDate();
        if (date!=null && date.isBefore(staffLeave.getStartDate()))
            return false;
        staffLeave.setAppStatus("1");
        staffLeaveMapper.updateStaffLeave(staffLeave);
        staffLeaveMapper.updateStaffLeaveStatus(staffLeave);
        return true;
    }
}
